package com.goldsprite.littlegame.screens.games.phase_1;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.physics.box2d.*;
import com.badlogic.gdx.math.Vector2;
import com.goldsprite.gdxcore.screens.GScreen;

public class Box2DExample extends GScreen {
    private World world; // 物理世界
    private Box2DDebugRenderer debugRenderer; // 调试渲染器
    private OrthographicCamera camera; // 摄像机

    @Override
    public void create() {
        // 初始化摄像机
        camera = new OrthographicCamera(40, 20); // 视口宽50米，高30米
        camera.position.set(0, 0, 0); // 将摄像机对准中心
        camera.update();

        // 初始化物理世界，设置重力
        world = new World(new Vector2(0, -9.8f), true); // 重力方向为负y轴

        // 初始化调试渲染器
        debugRenderer = new Box2DDebugRenderer();

        // 创建地面
        createGround();

        // 创建弹跳的矩形
        createBouncingRectangle();
    }

    private void createGround() {
        // 定义地面的刚体
        BodyDef groundBodyDef = new BodyDef();
        groundBodyDef.position.set(0, 0); // 地面在(0, 0)处
        Body groundBody = world.createBody(groundBodyDef);

        // 定义地面的形状
        PolygonShape groundBox = new PolygonShape();
        groundBox.setAsBox(25, 1); // 地面宽50米，高2米

        // 创建地面的夹具
        groundBody.createFixture(groundBox, 0); // 密度为0，表示静止不动
        groundBox.dispose();
    }

    private void createBouncingRectangle() {
        // 定义矩形的刚体
        BodyDef rectangleBodyDef = new BodyDef();
        rectangleBodyDef.type = BodyDef.BodyType.DynamicBody; // 动态刚体
        rectangleBodyDef.position.set(0, 10); // 矩形初始位置为(0, 10)
        Body rectangleBody = world.createBody(rectangleBodyDef);

        // 定义矩形的形状
        PolygonShape rectangleBox = new PolygonShape();
        rectangleBox.setAsBox(2, 1); // 矩形宽4米，高2米

        // 定义矩形的夹具属性
        FixtureDef fixtureDef = new FixtureDef();
        fixtureDef.shape = rectangleBox;
        fixtureDef.density = 1.0f; // 密度
        fixtureDef.friction = 0.4f; // 摩擦力
        fixtureDef.restitution = 0.8f; // 弹性系数，控制弹跳高度

        // 创建矩形的夹具
        rectangleBody.createFixture(fixtureDef);
        rectangleBox.dispose();
    }

    @Override
    public void render(float delta) {
        // 清屏
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        // 更新物理世界
        world.step(1 / 60f, 6, 2);

        // 渲染调试视图
        debugRenderer.render(world, camera.combined);
    }

    @Override
    public void dispose() {
        // 清理资源
        world.dispose();
        debugRenderer.dispose();
    }
}

